package com.nsy.ovulatorymonitor.domain;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.util.Log;

public final class UserInfoContract {
	private Context _context = null;
	public UserInfoContract(Context context){
		_context = context;
	}
	
	private String _LogTag = "UserInfo"; 
	
	public static abstract class UserInfoEntry implements BaseColumns
	{
		public static final String TABLE_NAME = "UserInfo";         
		public static final String COLUMN_NAME_USERINFO_ID = "ID"; 
		public static final String COLUMN_NAME_USERINFO_EMAIL = "EMAIL";
		public static final String COLUMN_NAME_USERINFO_PASSWORD = "PASSWORD";
	}
	
	
	public int Login(String email,String password)
	{
		int result = -1;
		
		try
		{
			OvulatoryMonitorDbHelper mDbHelper = new OvulatoryMonitorDbHelper(_context);
			SQLiteDatabase db = mDbHelper.getReadableDatabase();
			
			String selection = UserInfoEntry.COLUMN_NAME_USERINFO_EMAIL + " LIKE ?"; 
			String[] selectionArgs = { email };
			String[] projection = {     UserInfoEntry.COLUMN_NAME_USERINFO_PASSWORD };   
			
			Cursor cursor = db.query(UserInfoEntry.TABLE_NAME,
					projection,                          
					selection,                             
					selectionArgs,                           
					null,                                     
					null,                                     
					null);
			
			if(cursor.moveToFirst())
			{
				String fetchPassword = cursor.getString(cursor.getColumnIndexOrThrow(UserInfoEntry.COLUMN_NAME_USERINFO_PASSWORD) );
				
				if(fetchPassword.equals(password))
				{
					result = 1;
				}
				else
				{
					result = 2;
				}
			}
			else
			{
				result = 3;
			}
			
			if(cursor!= null)
			{
				if(!cursor.isClosed())
				{
					cursor.close();
				}
			}
		}
		catch(Exception ex)
		{
			Log.e(_LogTag,ex.getMessage());
			result = -1;
		}
		return result;
	}
	
	public long Register(String email,String password)
	{
		try
		{
			OvulatoryMonitorDbHelper mDbHelper = new OvulatoryMonitorDbHelper(_context);
			SQLiteDatabase db = mDbHelper.getWritableDatabase();
			
			ContentValues values = new ContentValues(); 
			values.put(UserInfoEntry.COLUMN_NAME_USERINFO_EMAIL, email); 
			values.put(UserInfoEntry.COLUMN_NAME_USERINFO_PASSWORD, password); 
			
			return db.insert(UserInfoEntry.TABLE_NAME, null, values);
		}
		catch(Exception ex)
		{
			Log.e(_LogTag,ex.getMessage());
		}
		return -1;
	}
}
